﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BibMan.model;
using BibMan.controller;
using BibMan.model.database;

namespace BibMan.gui {
    public partial class PinListBox : ListBox {
        public PinListBox() {
            InitializeComponent();

            Model.Instance.DatabaseLoaded += OnDatabaseLoaded;
            Model.Instance.DatabaseCreated += OnDatabaseLoaded;
        }

        public PinListBox(IContainer container) : this() {
            container.Add(this);
        }

        private String AllReferencesPin = "All";
        private String UnPinnedReferences = "Unpinned";
        public List<String> References {
            get {
                if (SelectedItem.ToString() == AllReferencesPin) {
                    return Model.Instance.Database.ConvertAll<String>(r => r.Id);
                }
                if (SelectedItem.ToString() == UnPinnedReferences) {
                    return Model.Instance.Database.Where(e => e.Pins.Count == 0).ToList().ConvertAll<String>(r => r.Id);
                }
                return Model.Instance.Database.Pins[SelectedItem.ToString()].References.ToList().ConvertAll<String>(r => r.Id);
            }
        }

        public void OnDatabaseLoaded() {
            Model.Instance.Database.Pins.Cleared -= Reset;
            Model.Instance.Database.Pins.Cleared += Reset;
            Model.Instance.Database.Pins.Added -= PinAdded;
            Model.Instance.Database.Pins.Added += PinAdded;
            Model.Instance.Database.Pins.Removed -= PinRemoved;
            Model.Instance.Database.Pins.Removed += PinRemoved;
            Reset();
        }

        private void Reset() {
            this.Items.Clear();
            this.Items.Add(AllReferencesPin);
            this.Items.Add(UnPinnedReferences);
            foreach (String pin in Model.Instance.Database.Pins.Keys) {
                this.Items.Add(pin);
            }
            this.SelectedIndex = 0;
        }

        private void PinAdded(String name, Pin pin) {
            this.Items.Add(name);
        }

        private void PinRemoved(String name, Pin pin) {
            this.Items.Remove(name);
        }
    }
}
